package org.fing.edu.uy.esbadp.action.delayer;

import java.util.logging.Level;

import org.fing.edu.uy.esbadp.assertion.AssertProperty;
import org.fing.edu.uy.esbadp.core.AdpFlowConstants;
import org.fing.edu.uy.esbadp.core.AdpFlowInterface;
import org.fing.edu.uy.esbadp.core.AdpFlowRET;
import org.fing.edu.uy.esbadp.core.AdpFlowTree;
import org.fing.edu.uy.esbadp.core.entity.GenericTreeNode;
import org.fing.edu.uy.esbadp.logger.LoggerADP;
import org.jboss.internal.soa.esb.assertion.AssertArgument;
import org.jboss.soa.esb.actions.ActionProcessingException;
import org.jboss.soa.esb.actions.annotation.Process;
import org.jboss.soa.esb.message.Message;

public class DelayerAction {
	
	private static java.util.logging.Logger logger = LoggerADP.getLogger(DelayerAction.class.getSimpleName());
	
	public DelayerAction() {
		
	}

	/**
	 * @param message
	 */
	@Process
	public Message process(Message message) throws ActionProcessingException {
		
		if(logger.isLoggable(LoggerADP.DEBUG_LEVEL)){
			logger.log(LoggerADP.DEBUG_LEVEL, "Process Action -> {0}", this.getClass().getName());
		}
		
		AssertArgument.isNotNull(message, "message");
		AssertProperty.isNotNull(message, AdpFlowConstants.PropertyFlowServices);

		//se obtiene el arbol con las acciones a realizar
		AdpFlowTree adpFlowTree = (AdpFlowTree) message.getProperties().getProperty(AdpFlowConstants.PropertyFlowServices);
		GenericTreeNode<AdpFlowInterface> treeNode = adpFlowTree.getCurrent();
		
		//como esta accion no tiene que decidir el proximo nodo es el primer hijo
		GenericTreeNode<AdpFlowInterface> nextCurrent = treeNode.getChildren().size() > 0 ? treeNode.getChildAt(0) : null;
		adpFlowTree.setCurrent(nextCurrent);
		
		AdpFlowRET adpFlowAction = (AdpFlowRET) treeNode.getData();
		
		//Delay de acuerdo a lo que se halla definido en la accion
		try {
			Thread.sleep(adpFlowAction.getDelay());
		} catch (Exception ex) {
			logger.log(Level.SEVERE, "Exception in DelayerAction when sleep flow.", ex);
		}
		return message;
	}

}
